<template>
    <div class="wh-100% flex gap-20px">
        <div class="w-70% h-full flex flex-col gap-10px">
            <div class="relative w-full">
                <RoomFilter @filter-room="handleFilterRoom" />
            </div>
            <n-spin class="flex-1 overflow-scroll" :show="filterLoading">
                <div
                    v-if="filterRooms.length === 0 || roomRequirement === null"
                    class="w-full h-500px flex-center"
                >
                    <n-result
                        status="404"
                        title="暂无符合条件的会议室"
                        description="总有些事是无法办的，比如开会。"
                    >
                    </n-result>
                </div>
                <div v-else>
                    <n-grid
                        responsive="screen"
                        cols="s:2 m:3 l:4"
                        :x-gap="20"
                        :y-gap="20"
                    >
                        <n-gi
                            v-for="item in filterRooms"
                            :key="item.id"
                            @click="currentRoom = item"
                            class="bg-#fff hover:shadow-xl rounded-10px cursor-pointer flex"
                        >
                            <div class="h-full w-64px rounded-full flex-center">
                                <n-icon :component="Easel" :size="36" />
                            </div>
                            <div class="flex-1 box-border p-10px">
                                <div class="mb-4px">{{ item.name }}</div>
                                <n-tag size="small" type="primary">
                                    {{ item.hourlyRate }}￥/时
                                </n-tag>
                            </div>
                        </n-gi>
                    </n-grid>
                </div>
            </n-spin>
        </div>
        <div class="w-30% h-full">
            <n-card v-if="currentRoom" class="h-full overflow-scroll">
                <!-- <div></div> -->
                <template #header>会议室预约</template>
                <div class="overflow-hidden">
                    <RoomDetail :room="currentRoom" />
                </div>
                <div>
                    <n-divider>订单详情</n-divider>
                    <n-list hoverable>
                        <n-list-item>
                            <n-thing
                                title="预约日期"
                                :title-extra="
                                    new Date(
                                        roomRequirement!.reserveDate!
                                    ).toLocaleDateString()
                                "
                            ></n-thing>
                        </n-list-item>
                        <n-list-item>
                            <n-thing
                                title="使用时间"
                                :title-extra="`${roomRequirement?.startTime}:00-${roomRequirement?.endTime}:00`"
                            ></n-thing>
                        </n-list-item>
                        <n-list-item>
                            <n-thing title="订单金额">
                                <template #header-extra>
                                    <n-tag size="small" type="primary">
                                        {{
                                            (roomRequirement!.endTime! -
                                                roomRequirement!.startTime!) *
                                            currentRoom?.hourlyRate
                                        }}元
                                    </n-tag>
                                </template>
                            </n-thing>
                        </n-list-item>
                    </n-list>
                </div>
                <template #footer>
                    <div class="w-full flex justify-end">
                        <n-button
                            secondary
                            type="primary"
                            @click="handleSubmitOrder"
                        >
                            提交订单
                        </n-button>
                    </div>
                </template>
            </n-card>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { getStore } from "@/store";
import { useRouter } from "vue-router";

import type { MeetingRoom } from "@/service/api/types/room";
import type { Requirement, Order } from "@/service/api/types/reservation";

import { Easel } from "@vicons/ionicons5";
import { filterUseableRooms } from "@/service/api/modules/room";

import RoomFilter from "../components/room-filter/index.vue";
import RoomDetail from "../../admin/components/room-detail/index.vue";

import { submitOrder, getUnpaidOrder } from "@/service/api/modules/order";

defineOptions({
    name: "reserve",
});

const router = useRouter();
const userStore = getStore("user");
const reservationStore = getStore("reservation");

const filterLoading = ref(false);

// 筛选的会议室列表
const filterRooms = ref<MeetingRoom[]>([]);
// 会议室筛选条件
const roomRequirement = ref<Requirement | null>(null);
// 当前选中的会议室
const currentRoom = ref<MeetingRoom | null>(null);

onMounted(async () => {
    const dialogOptions = {
        title: "提示",
        content: "您有未支付的订单，请前往支付",
        closable: false,
        maskClosable: false,
        positiveText: "前往支付",
        onPositiveClick: () => {
            router.push("/layout/payment");
        },
    };

    if (reservationStore.getUnpaidOrder) {
        window.NDialog.info(dialogOptions);
        return;
    }
    // 先获取用户是否有未支付的订单，有则需要跳转处理，否则无法预约
    const costomerId = userStore.getUserInfo.id;
    try {
        const res = await getUnpaidOrder(costomerId);
        if (res) {
            reservationStore.setUnpaidOrder(res);
            window.NDialog.info(dialogOptions);
        }
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
});

const handleFilterRoom = async (requirement: Requirement) => {
    roomRequirement.value = requirement;

    filterRooms.value = [];
    currentRoom.value = null;

    filterLoading.value = true;
    try {
        filterRooms.value = await filterUseableRooms(requirement);
        console.log(filterRooms.value);
        filterRooms.value.sort((a, b) => {
            return a.hourlyRate - b.hourlyRate;
        });
    } catch (err) {
        window.NMessage.error((err as Error).message);
    } finally {
        filterLoading.value = false;
    }
};

const handleSubmitOrder = () => {
    window.NDialog.info({
        title: "提交订单",
        content: "确认提交订单？",
        closable: false,
        positiveText: "确认",
        negativeText: "取消",
        onPositiveClick: async () => {
            if (!currentRoom.value || !roomRequirement.value) return;
            const order: Order = {
                customerId: userStore.getUserInfo.id,
                roomId: currentRoom.value.id!,
                requirement: roomRequirement.value!,
                amount:
                    (roomRequirement.value.endTime! -
                        roomRequirement.value.startTime!) *
                    currentRoom.value.hourlyRate,
                payment_status: "unpaid",
                paymentTime: null,
                createdTime: Date.now(),
            };
            try {
                order.id = await submitOrder(order);
                reservationStore.setUnpaidOrder(order);
                router.push("/layout/payment");
            } catch (err) {
                window.NMessage.error((err as Error).message);
            }
        },
    });
};
</script>

<style scoped></style>
